/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.pp.persistance;

import java.io.Serializable;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import com.pp.entites.Hse;
import java.util.ArrayList;
import java.util.List;
import com.pp.entites.Personnel;
import com.pp.entites.Mobiledevice;
import com.pp.entites.Rack;
import com.pp.entites.Site;
import com.pp.persistance.exceptions.IllegalOrphanException;
import com.pp.persistance.exceptions.NonexistentEntityException;
import com.pp.persistance.exceptions.PreexistingEntityException;
import com.pp.persistance.exceptions.RollbackFailureException;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.transaction.UserTransaction;

/**
 *
 * @author arnaud
 */
public class SiteJpaController implements Serializable {

    public SiteJpaController(UserTransaction utx, EntityManagerFactory emf) {
        this.utx = utx;
        this.emf = emf;
    }
    private UserTransaction utx = null;
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Site site) throws PreexistingEntityException, RollbackFailureException, Exception {
        if (site.getHseList() == null) {
            site.setHseList(new ArrayList<Hse>());
        }
        if (site.getPersonnelList() == null) {
            site.setPersonnelList(new ArrayList<Personnel>());
        }
        if (site.getMobiledeviceList() == null) {
            site.setMobiledeviceList(new ArrayList<Mobiledevice>());
        }
        if (site.getRackList() == null) {
            site.setRackList(new ArrayList<Rack>());
        }
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            List<Hse> attachedHseList = new ArrayList<Hse>();
            for (Hse hseListHseToAttach : site.getHseList()) {
                hseListHseToAttach = em.getReference(hseListHseToAttach.getClass(), hseListHseToAttach.getId());
                attachedHseList.add(hseListHseToAttach);
            }
            site.setHseList(attachedHseList);
            List<Personnel> attachedPersonnelList = new ArrayList<Personnel>();
            for (Personnel personnelListPersonnelToAttach : site.getPersonnelList()) {
                personnelListPersonnelToAttach = em.getReference(personnelListPersonnelToAttach.getClass(), personnelListPersonnelToAttach.getId());
                attachedPersonnelList.add(personnelListPersonnelToAttach);
            }
            site.setPersonnelList(attachedPersonnelList);
            List<Mobiledevice> attachedMobiledeviceList = new ArrayList<Mobiledevice>();
            for (Mobiledevice mobiledeviceListMobiledeviceToAttach : site.getMobiledeviceList()) {
                mobiledeviceListMobiledeviceToAttach = em.getReference(mobiledeviceListMobiledeviceToAttach.getClass(), mobiledeviceListMobiledeviceToAttach.getId());
                attachedMobiledeviceList.add(mobiledeviceListMobiledeviceToAttach);
            }
            site.setMobiledeviceList(attachedMobiledeviceList);
            List<Rack> attachedRackList = new ArrayList<Rack>();
            for (Rack rackListRackToAttach : site.getRackList()) {
                rackListRackToAttach = em.getReference(rackListRackToAttach.getClass(), rackListRackToAttach.getId());
                attachedRackList.add(rackListRackToAttach);
            }
            site.setRackList(attachedRackList);
            em.persist(site);
            for (Hse hseListHse : site.getHseList()) {
                Site oldIdsiteOfHseListHse = hseListHse.getIdsite();
                hseListHse.setIdsite(site);
                hseListHse = em.merge(hseListHse);
                if (oldIdsiteOfHseListHse != null) {
                    oldIdsiteOfHseListHse.getHseList().remove(hseListHse);
                    oldIdsiteOfHseListHse = em.merge(oldIdsiteOfHseListHse);
                }
            }
            for (Personnel personnelListPersonnel : site.getPersonnelList()) {
                Site oldIdsiteOfPersonnelListPersonnel = personnelListPersonnel.getIdsite();
                personnelListPersonnel.setIdsite(site);
                personnelListPersonnel = em.merge(personnelListPersonnel);
                if (oldIdsiteOfPersonnelListPersonnel != null) {
                    oldIdsiteOfPersonnelListPersonnel.getPersonnelList().remove(personnelListPersonnel);
                    oldIdsiteOfPersonnelListPersonnel = em.merge(oldIdsiteOfPersonnelListPersonnel);
                }
            }
            for (Mobiledevice mobiledeviceListMobiledevice : site.getMobiledeviceList()) {
                Site oldIdsiteOfMobiledeviceListMobiledevice = mobiledeviceListMobiledevice.getIdsite();
                mobiledeviceListMobiledevice.setIdsite(site);
                mobiledeviceListMobiledevice = em.merge(mobiledeviceListMobiledevice);
                if (oldIdsiteOfMobiledeviceListMobiledevice != null) {
                    oldIdsiteOfMobiledeviceListMobiledevice.getMobiledeviceList().remove(mobiledeviceListMobiledevice);
                    oldIdsiteOfMobiledeviceListMobiledevice = em.merge(oldIdsiteOfMobiledeviceListMobiledevice);
                }
            }
            for (Rack rackListRack : site.getRackList()) {
                Site oldIdsiteOfRackListRack = rackListRack.getIdsite();
                rackListRack.setIdsite(site);
                rackListRack = em.merge(rackListRack);
                if (oldIdsiteOfRackListRack != null) {
                    oldIdsiteOfRackListRack.getRackList().remove(rackListRack);
                    oldIdsiteOfRackListRack = em.merge(oldIdsiteOfRackListRack);
                }
            }
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            if (findSite(site.getId()) != null) {
                throw new PreexistingEntityException("Site " + site + " already exists.", ex);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Site site) throws IllegalOrphanException, NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Site persistentSite = em.find(Site.class, site.getId());
            List<Hse> hseListOld = persistentSite.getHseList();
            List<Hse> hseListNew = site.getHseList();
            List<Personnel> personnelListOld = persistentSite.getPersonnelList();
            List<Personnel> personnelListNew = site.getPersonnelList();
            List<Mobiledevice> mobiledeviceListOld = persistentSite.getMobiledeviceList();
            List<Mobiledevice> mobiledeviceListNew = site.getMobiledeviceList();
            List<Rack> rackListOld = persistentSite.getRackList();
            List<Rack> rackListNew = site.getRackList();
            List<String> illegalOrphanMessages = null;
            for (Hse hseListOldHse : hseListOld) {
                if (!hseListNew.contains(hseListOldHse)) {
                    if (illegalOrphanMessages == null) {
                        illegalOrphanMessages = new ArrayList<String>();
                    }
                    illegalOrphanMessages.add("You must retain Hse " + hseListOldHse + " since its idsite field is not nullable.");
                }
            }
            for (Mobiledevice mobiledeviceListOldMobiledevice : mobiledeviceListOld) {
                if (!mobiledeviceListNew.contains(mobiledeviceListOldMobiledevice)) {
                    if (illegalOrphanMessages == null) {
                        illegalOrphanMessages = new ArrayList<String>();
                    }
                    illegalOrphanMessages.add("You must retain Mobiledevice " + mobiledeviceListOldMobiledevice + " since its idsite field is not nullable.");
                }
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            List<Hse> attachedHseListNew = new ArrayList<Hse>();
            for (Hse hseListNewHseToAttach : hseListNew) {
                hseListNewHseToAttach = em.getReference(hseListNewHseToAttach.getClass(), hseListNewHseToAttach.getId());
                attachedHseListNew.add(hseListNewHseToAttach);
            }
            hseListNew = attachedHseListNew;
            site.setHseList(hseListNew);
            List<Personnel> attachedPersonnelListNew = new ArrayList<Personnel>();
            for (Personnel personnelListNewPersonnelToAttach : personnelListNew) {
                personnelListNewPersonnelToAttach = em.getReference(personnelListNewPersonnelToAttach.getClass(), personnelListNewPersonnelToAttach.getId());
                attachedPersonnelListNew.add(personnelListNewPersonnelToAttach);
            }
            personnelListNew = attachedPersonnelListNew;
            site.setPersonnelList(personnelListNew);
            List<Mobiledevice> attachedMobiledeviceListNew = new ArrayList<Mobiledevice>();
            for (Mobiledevice mobiledeviceListNewMobiledeviceToAttach : mobiledeviceListNew) {
                mobiledeviceListNewMobiledeviceToAttach = em.getReference(mobiledeviceListNewMobiledeviceToAttach.getClass(), mobiledeviceListNewMobiledeviceToAttach.getId());
                attachedMobiledeviceListNew.add(mobiledeviceListNewMobiledeviceToAttach);
            }
            mobiledeviceListNew = attachedMobiledeviceListNew;
            site.setMobiledeviceList(mobiledeviceListNew);
            List<Rack> attachedRackListNew = new ArrayList<Rack>();
            for (Rack rackListNewRackToAttach : rackListNew) {
                rackListNewRackToAttach = em.getReference(rackListNewRackToAttach.getClass(), rackListNewRackToAttach.getId());
                attachedRackListNew.add(rackListNewRackToAttach);
            }
            rackListNew = attachedRackListNew;
            site.setRackList(rackListNew);
            site = em.merge(site);
            for (Hse hseListNewHse : hseListNew) {
                if (!hseListOld.contains(hseListNewHse)) {
                    Site oldIdsiteOfHseListNewHse = hseListNewHse.getIdsite();
                    hseListNewHse.setIdsite(site);
                    hseListNewHse = em.merge(hseListNewHse);
                    if (oldIdsiteOfHseListNewHse != null && !oldIdsiteOfHseListNewHse.equals(site)) {
                        oldIdsiteOfHseListNewHse.getHseList().remove(hseListNewHse);
                        oldIdsiteOfHseListNewHse = em.merge(oldIdsiteOfHseListNewHse);
                    }
                }
            }
            for (Personnel personnelListOldPersonnel : personnelListOld) {
                if (!personnelListNew.contains(personnelListOldPersonnel)) {
                    personnelListOldPersonnel.setIdsite(null);
                    personnelListOldPersonnel = em.merge(personnelListOldPersonnel);
                }
            }
            for (Personnel personnelListNewPersonnel : personnelListNew) {
                if (!personnelListOld.contains(personnelListNewPersonnel)) {
                    Site oldIdsiteOfPersonnelListNewPersonnel = personnelListNewPersonnel.getIdsite();
                    personnelListNewPersonnel.setIdsite(site);
                    personnelListNewPersonnel = em.merge(personnelListNewPersonnel);
                    if (oldIdsiteOfPersonnelListNewPersonnel != null && !oldIdsiteOfPersonnelListNewPersonnel.equals(site)) {
                        oldIdsiteOfPersonnelListNewPersonnel.getPersonnelList().remove(personnelListNewPersonnel);
                        oldIdsiteOfPersonnelListNewPersonnel = em.merge(oldIdsiteOfPersonnelListNewPersonnel);
                    }
                }
            }
            for (Mobiledevice mobiledeviceListNewMobiledevice : mobiledeviceListNew) {
                if (!mobiledeviceListOld.contains(mobiledeviceListNewMobiledevice)) {
                    Site oldIdsiteOfMobiledeviceListNewMobiledevice = mobiledeviceListNewMobiledevice.getIdsite();
                    mobiledeviceListNewMobiledevice.setIdsite(site);
                    mobiledeviceListNewMobiledevice = em.merge(mobiledeviceListNewMobiledevice);
                    if (oldIdsiteOfMobiledeviceListNewMobiledevice != null && !oldIdsiteOfMobiledeviceListNewMobiledevice.equals(site)) {
                        oldIdsiteOfMobiledeviceListNewMobiledevice.getMobiledeviceList().remove(mobiledeviceListNewMobiledevice);
                        oldIdsiteOfMobiledeviceListNewMobiledevice = em.merge(oldIdsiteOfMobiledeviceListNewMobiledevice);
                    }
                }
            }
            for (Rack rackListOldRack : rackListOld) {
                if (!rackListNew.contains(rackListOldRack)) {
                    rackListOldRack.setIdsite(null);
                    rackListOldRack = em.merge(rackListOldRack);
                }
            }
            for (Rack rackListNewRack : rackListNew) {
                if (!rackListOld.contains(rackListNewRack)) {
                    Site oldIdsiteOfRackListNewRack = rackListNewRack.getIdsite();
                    rackListNewRack.setIdsite(site);
                    rackListNewRack = em.merge(rackListNewRack);
                    if (oldIdsiteOfRackListNewRack != null && !oldIdsiteOfRackListNewRack.equals(site)) {
                        oldIdsiteOfRackListNewRack.getRackList().remove(rackListNewRack);
                        oldIdsiteOfRackListNewRack = em.merge(oldIdsiteOfRackListNewRack);
                    }
                }
            }
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = site.getId();
                if (findSite(id) == null) {
                    throw new NonexistentEntityException("The site with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Integer id) throws IllegalOrphanException, NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Site site;
            try {
                site = em.getReference(Site.class, id);
                site.getId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The site with id " + id + " no longer exists.", enfe);
            }
            List<String> illegalOrphanMessages = null;
            List<Hse> hseListOrphanCheck = site.getHseList();
            for (Hse hseListOrphanCheckHse : hseListOrphanCheck) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("This Site (" + site + ") cannot be destroyed since the Hse " + hseListOrphanCheckHse + " in its hseList field has a non-nullable idsite field.");
            }
            List<Mobiledevice> mobiledeviceListOrphanCheck = site.getMobiledeviceList();
            for (Mobiledevice mobiledeviceListOrphanCheckMobiledevice : mobiledeviceListOrphanCheck) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("This Site (" + site + ") cannot be destroyed since the Mobiledevice " + mobiledeviceListOrphanCheckMobiledevice + " in its mobiledeviceList field has a non-nullable idsite field.");
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            List<Personnel> personnelList = site.getPersonnelList();
            for (Personnel personnelListPersonnel : personnelList) {
                personnelListPersonnel.setIdsite(null);
                personnelListPersonnel = em.merge(personnelListPersonnel);
            }
            List<Rack> rackList = site.getRackList();
            for (Rack rackListRack : rackList) {
                rackListRack.setIdsite(null);
                rackListRack = em.merge(rackListRack);
            }
            em.remove(site);
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Site> findSiteEntities() {
        return findSiteEntities(true, -1, -1);
    }

    public List<Site> findSiteEntities(int maxResults, int firstResult) {
        return findSiteEntities(false, maxResults, firstResult);
    }

    private List<Site> findSiteEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Site.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Site findSite(Integer id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Site.class, id);
        } finally {
            em.close();
        }
    }

    public int getSiteCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Site> rt = cq.from(Site.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
    
}
